package com.newmodelclient.baselib.fragment;

import android.app.Activity;
import android.content.Context;
import android.content.Intent;
import android.graphics.Color;
import android.graphics.Typeface;
import android.os.Build;
import android.os.Bundle;
import android.text.SpannableString;
import android.text.Spanned;
import android.text.SpannedString;
import android.text.style.AbsoluteSizeSpan;
import android.util.Log;
import android.view.Gravity;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.view.Window;
import android.view.WindowManager;
import android.view.inputmethod.InputMethodManager;
import android.widget.EditText;
import android.widget.FrameLayout;
import android.widget.Toast;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;
import androidx.fragment.app.Fragment;
import androidx.swiperefreshlayout.widget.SwipeRefreshLayout;

import com.alibaba.android.arouter.launcher.ARouter;
import com.bumptech.glide.Glide;
import com.kaopiz.kprogresshud.KProgressHUD;
import com.newmodelclient.baselib.BuildConfig;
import com.newmodelclient.baselib.R;
import com.newmodelclient.baselib.enums.FCPageViewState;
import com.newmodelclient.baselib.presenter.FCBasePresenter;
import com.newmodelclient.baselib.presenter.IFCBaseView;
import com.newmodelclient.baselib.util.TUtil;
import com.newmodelclient.baselib.util.ToastUtil;
import com.newmodelclient.baselib.widget.FCNavigationAction;
import com.newmodelclient.baselib.widget.FCNavigationBar;
import com.newmodelclient.baselib.widget.FCPageLoading;
import com.newmodelclient.baselib.widget.FCPageStateClickListener;
import com.newmodelclient.baselib.widget.FCPageStateView;
import com.newmodelclient.baselib.widget.IFCNavigationListener;

import org.greenrobot.eventbus.EventBus;

import java.io.Serializable;
import java.util.List;
import java.util.Timer;
import java.util.TimerTask;

import butterknife.ButterKnife;
import butterknife.Unbinder;

/**
 * 文件名：FCBaseFragment
 * 描 述：Fragment父类
 * 作 者：gyq
 * 时 间：2021-1-22
 */
public abstract class FCBaseFragment<T extends FCBasePresenter> extends Fragment implements IFCBaseView, FCPageStateClickListener {

    //泛型 presenter
    protected T mPresenter;
    //上下文
    private Context mContext;
    //基类(Activity)所使用的TAG标签
    //通用字体
    protected Typeface mIconFont;
    //主视图
    protected View mRootView;
    //内容试图
    protected FrameLayout mContainerView;
    //导航栏
    protected FCNavigationBar mNavigationBar;
    //pageLoading
    private FCPageLoading mPageLoading;
    //commitLoading
    protected KProgressHUD mCommitLoading;
    //默认页面
    protected FCPageStateView mStateView;
    private Unbinder unbinder;

    //下拉刷新控件
    private SwipeRefreshLayout mRefreshView;

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      初始化
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Nullable
    @Override
    public View onCreateView(@NonNull LayoutInflater inflater, @Nullable ViewGroup container, @Nullable Bundle savedInstanceState) {
        if (null == mRootView) {
            this.mContext = getActivity();
            //获取公用字体
            mIconFont = Typeface.createFromAsset(mContext.getAssets(), "fonts/iconfont.ttf");
            //初始化view
            initViews(inflater,container);
            //初始化导航栏
            initNavigationBar();
            //初始化任务
            initTasks();
            //ButterKnife绑定
            unbinder =  ButterKnife.bind(this,mRootView);
            //初始化ui和数据
            requireInitUIAndData(savedInstanceState);
        } else {
            ViewGroup parent = (ViewGroup) mRootView.getParent();
            if (null != parent) {
                parent.removeView(mRootView);
            }
        }
        return mRootView;
    }

    /**
     * 初始化任务
     * */
    protected void initTasks() {
        //绑定路由
        ARouter.getInstance().inject(this);
        //绑定eventBus
        if (useEventBus()) {
            EventBus.getDefault().register(this);
        }
        //初始化presenter(如果子类不是FCFragmentHostActivity)
        mPresenter = TUtil.getT(this, 0);
        if (mPresenter != null) {
            mPresenter.setIView(this);
        }
    }

    protected void initViews(LayoutInflater inflater, ViewGroup container) {
        //总布局
        int rootViewId = requireGetLayoutId();
        if (useRefreshLayout()) {
            mRootView = inflater.inflate(R.layout.activity_base_refresh_gzg, container, false);
            mRefreshView = mRootView.findViewById(R.id.sl_base_refresh);
        } else {
            mRootView = inflater.inflate(R.layout.activity_base_gzg, container, false);
        }
        mContainerView = mRootView.findViewById(R.id.fl_base_container);
        View contentView = getActivity().getLayoutInflater().inflate(rootViewId, null);
        mContainerView.addView(contentView);
    }

    /**
     * 初始化导航栏
     * */
    private void initNavigationBar() {
        mNavigationBar = mRootView.findViewById(R.id.v_base_nav_bar);
        mNavigationBar.setGzgNavigationListener(new IFCNavigationListener() {
            @Override
            public void onNavigationClickListen(int action) {
                switch (action) {
                    case FCNavigationAction.NAV_LEFT_CLICK: {
                        onNavigationLeftClick();
                    }
                    break;
                    case FCNavigationAction.NAV_RIGHT_CLICK: {
                        onNavigationRightClick();
                    }
                    break;
                }
            }
        });
        if (isFullscreen()) {
            mNavigationBar.setVisibility(View.GONE);
        }
        requireSetCustomNavigationBar(mNavigationBar);
    }

    /**
     * 导航栏事件
     * */
    protected void onNavigationLeftClick() {
        if (getActivity() != null) {
            getActivity().finish();
        }
    }

    protected void onNavigationRightClick() {
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      必须子类实现方法
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 获取布局
     * */
    protected abstract int requireGetLayoutId();

    /**
     * 自定义导航栏
     * */
    protected abstract void requireSetCustomNavigationBar(FCNavigationBar navigationBar);

    /**
     * 初始化UI和数据
     * */
    protected abstract void requireInitUIAndData(Bundle savedInstanceState);

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      控制方法
    //
    /////////////////////////////////////////////////////////////////////////////////

    /**
     * 是否使用eventBus
     * */
    protected boolean useEventBus() {
        return false;
    }

    /**
     * 是否全屏幕
     * */
    protected boolean isFullscreen() {
        return false;
    }

    /**
    * 是否使用下拉刷新页面
    * */
    protected boolean useRefreshLayout() {
        return false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      IFCBaseView
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public Context context() {
        return mContext;
    }

    /**
     * 显示页面指示器
     * */
    @Override
    public void baseShowPageLoading(boolean isCanTouchOutSide) {
        if (getActivity() != null) {
            if (mPageLoading == null) {
                mPageLoading = new FCPageLoading(getActivity());
                mContainerView.addView(mPageLoading);
            }
            if (isCanTouchOutSide) {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.WRAP_CONTENT, FrameLayout.LayoutParams.WRAP_CONTENT);
                layoutParams.gravity = Gravity.CENTER;
                mPageLoading.setLayoutParams(layoutParams);
            } else {
                FrameLayout.LayoutParams layoutParams = new FrameLayout.LayoutParams(FrameLayout.LayoutParams.MATCH_PARENT, FrameLayout.LayoutParams.MATCH_PARENT);
                mPageLoading.setLayoutParams(layoutParams);
            }
            mPageLoading.showProgressLoading();
        }
    }

    /**
     * 隐藏页面指示器
     * */
    @Override
    public void baseHiddenPageLoading() {
        if (mPageLoading != null) {
            mPageLoading.hiddenLoading();
        }
    }

    /**
     * 显示提交指示器
     * */
    @Override
    public void baseShowCommitLoading(String msg) {
        if (mCommitLoading == null && getActivity() != null) {
            mCommitLoading = KProgressHUD.create(getActivity())
                    .setStyle(KProgressHUD.Style.SPIN_INDETERMINATE);
//            mCommitLoading.setSize(114,92);
            mCommitLoading.setBackgroundColor(Color.parseColor("#80000000"));
            mCommitLoading.setCancellable(false);
            if (msg != null && msg.length() > 0) {
                mCommitLoading.setLabel(msg);
            }
            if (getActivity() != null && !getActivity().isFinishing() && !mCommitLoading.isShowing()) {
                mCommitLoading.show();
            }
        } else if (getActivity() != null && !mCommitLoading.isShowing() && getActivity().hasWindowFocus()) {
            if (!getActivity().isFinishing()) {
                mCommitLoading.show();
            }
        }
    }

    /**
     * 隐藏提交指示器
     * */
    @Override
    public void baseHiddenCommitLoading() {
        if (mCommitLoading != null) {
            try {
                if (mCommitLoading.isShowing() && getActivity() != null && !getActivity().isFinishing()) {
                    mCommitLoading.dismiss();
                }
            } catch (IllegalArgumentException e) {
                e.printStackTrace();
            }
        }
        mCommitLoading = null;
    }

    /**
     * 刷新默认页面状态
     * */
    @Override
    public FCPageStateView baseRefreshPageState(int viewState) {
        return baseRefreshPageState(viewState,-1,null);
    }

    @Override
    public FCPageStateView baseRefreshPageState(int viewState, String msg) {
        return baseRefreshPageState(viewState,-1,msg);
    }

    @Override
    public FCPageStateView baseRefreshPageState(int viewState, int img, String msg) {
        if (viewState == FCPageViewState.PAGE_STATE_NORMAL) {
            if (mStateView != null) {
                mStateView.setViewState(viewState,img,msg);
                mStateView = null;
                return null;
            } else {
                return null;
            }
        }
        if (mStateView == null && mContainerView != null && getActivity() != null) {
            mStateView = new FCPageStateView(getActivity());
            mStateView.setFCPageStateClickListener(this);
            mContainerView.addView(mStateView);
        }
        if (mStateView != null) {
            mStateView.setViewState(viewState,img,msg);
            mStateView.bringToFront();
        }
        return mStateView;
    }

    /**
     * 刷新默认页面相对顶部偏移
     * */
    @Override
    public FCPageStateView baseRefreshPageStateTopOffset(int topOffset) {
        if (mStateView != null) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)mStateView.getLayoutParams();
            layoutParams.topMargin = topOffset;
            mStateView.setLayoutParams(layoutParams);
        }
        return mStateView;
    }

    @Override
    public FCPageStateView baseRefreshPageStateBottomOffset(int bottomOffset) {
        if (mStateView != null) {
            FrameLayout.LayoutParams layoutParams = (FrameLayout.LayoutParams)mStateView.getLayoutParams();
            layoutParams.bottomMargin = bottomOffset;
            mStateView.setLayoutParams(layoutParams);
        }
        return mStateView;
    }

    /**
     * 点击失败页面（重新刷新使用）
     * */
    @Override
    public void onClickPageStateErrorView() {

    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      统一回调（目前只处理失败）
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public void baseShowError() {
        //...
    }

    @Override
    public void baseShowError(String identifer) {
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      下拉刷新相关
    //
    /////////////////////////////////////////////////////////////////////////////////
    /**
    * 获取下拉刷新控件
    * */
    public SwipeRefreshLayout baseRefreshLayout() {
        if (useRefreshLayout()) {
            return mRefreshView;
        } else {
            throw new RuntimeException("没有设置下拉刷新布局: " + getClass());
        }
    }

    /**
    * 隐藏下拉刷新
    * */
    public void baseEndRefresh() {
        if (mRefreshView != null) {
            if(mRefreshView.isRefreshing()){
                mRefreshView.setRefreshing(false);
            }
        }
    }


    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      工具方法
    //
    /////////////////////////////////////////////////////////////////////////////////

    public void hideSoftInput(EditText et) {
        InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
        inputManager.hideSoftInputFromWindow(et.getWindowToken(), 0);
    }

    public void showSoftInput(EditText et) {
        et.setFocusable(true);
        et.setFocusableInTouchMode(true);
        et.requestFocus();

        //延迟弹出软键盘
        Timer timer = new Timer();
        timer.schedule(new TimerTask(){
            @Override
            public void run() {
                InputMethodManager inputManager = (InputMethodManager) et.getContext().getSystemService(Context.INPUT_METHOD_SERVICE);
                inputManager.showSoftInput(et, 0);
            }
        }, 300);
    }


    public void initEtHint(EditText editText, String hintText, int size){
        // 新建一个可以添加属性的文本对象
        SpannableString ss = new SpannableString(hintText);
        // 新建一个属性对象,设置文字的大小
        AbsoluteSizeSpan ass = new AbsoluteSizeSpan(size,true);
        // 附加属性到文本
        ss.setSpan(ass, 0, ss.length(), Spanned.SPAN_EXCLUSIVE_EXCLUSIVE);
        // 设置hint
        editText.setHint(new SpannedString(ss)); // 一定要进行转换,否则属性会消失
    }

    public void showToast(String str) {
        //Toast.makeText(mContext, str, Toast.LENGTH_SHORT).show();
        Toast toast = Toast.makeText(mContext,"", Toast.LENGTH_LONG);
        toast.setText(str);
        toast.setGravity(Gravity.CENTER, 0, 0);
        toast.show();
    }

    protected void startActivitryWithBundle(@NonNull Class clazz, String[][] val) {
        Intent intent = new Intent(mContext, clazz);
        Bundle bundle = new Bundle();
        if (val != null) {
            for (String[] aVal : val) {
                bundle.putString(aVal[0], aVal[1]);
            }
            intent.putExtras(bundle);
        }
        startActivity(intent);
    }

    /**
     * 参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent) author：FuZhi
     **/
    public void goTo(Class<?> goToCls, Object... values) {
        goTo(false, goToCls, values);
    }

    // <editor-fold defaultstate="collapsed" desc="参数传递(注：该方法为了方便传参,参数类型有局限性,传递特殊类型时单独构建Intent)">
    public void goTo(boolean finish, Class<?> goToCls, Object... values) {
        Intent intent = new Intent(getActivity(), goToCls);
        int i = 0;
        for (Object value : values) {
            Class<?> cls = value.getClass();
            String key = String.valueOf(i);
            if (cls == String.class) {
                intent.putExtra(key, (String) value);
            } else if (value instanceof Serializable) {
                intent.putExtra(key, (Serializable) value);
            } else if (cls == int[].class) {
                intent.putExtra(key, (int[]) value);
            } else if (cls == long[].class) {
                intent.putExtra(key, (long[]) value);
            } else if (cls == boolean[].class) {
                intent.putExtra(key, (boolean[]) value);
            } else if (cls == float[].class) {
                intent.putExtra(key, (float[]) value);
            } else if (cls == double[].class) {
                intent.putExtra(key, (double[]) value);
            } else if (cls == char[].class) {
                intent.putExtra(key, (char[]) value);
            } else if (cls == String[].class) {
                intent.putExtra(key, (String[]) value);
            } else if (cls == Bundle.class) {
                intent.putExtra(key, (Bundle) value);
            } else {
                throw new RuntimeException("不支持参数类型: " + cls.getSimpleName());
            }
            i++;
        }
        startActivity(intent);
        if (finish) {
            getActivity().finish();
        }
    }

    /**
     * 非空判断
     **/
    public static boolean isEmpty(Object... objs) {
        for (Object obj : objs) {
            if (obj == null) {
                return true;
            } else if (obj instanceof String && obj.equals("")) {
                return true;
            }
        }
        return false;
    }

    public static void VISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.VISIBLE);
        }
    }

    public static void INVISIBLE(View view) {
        if (view != null) {
            view.setVisibility(View.INVISIBLE);
        }
    }

    public static void GONE(View view) {
        if (view != null) {
            view.setVisibility(View.GONE);
        }
    }

    /**
     * 设置状态栏透明且全屏
     *
     * @param activity
     */
    public static void setFullScreenAndTransparent(Activity activity) {
        if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.KITKAT) {
            if (Build.VERSION.SDK_INT >= Build.VERSION_CODES.LOLLIPOP) {
                //5.x开始需要把颜色设置透明，否则导航栏会呈现系统默认的浅灰色
                Window window = activity.getWindow();
                View decorView = window.getDecorView();
                //两个 flag 要结合使用，表示让应用的主体内容占用系统状态栏的空间
                int option = View.SYSTEM_UI_FLAG_LAYOUT_FULLSCREEN | View.SYSTEM_UI_FLAG_LAYOUT_STABLE;
                decorView.setSystemUiVisibility(option);
                window.addFlags(WindowManager.LayoutParams.FLAG_DRAWS_SYSTEM_BAR_BACKGROUNDS);
                window.setStatusBarColor(Color.TRANSPARENT);
            } else {
                Window window = activity.getWindow();
                WindowManager.LayoutParams attributes = window.getAttributes();
                int flagTranslucentStatus = WindowManager.LayoutParams.FLAG_TRANSLUCENT_STATUS;
                attributes.flags |= flagTranslucentStatus;
                window.setAttributes(attributes);
            }
        }
    }

    /**
     * 显示Toast信息
     **/
    public void T(Object s) {
        ToastUtil.showToast(String.valueOf(s));
    }

    public boolean onBackpressed() {
        List<Fragment> fragments = getChildFragmentManager().getFragments();
        if (null != fragments && !fragments.isEmpty()) {
            for (Fragment fragment : fragments) {
                if (fragment.isResumed() && fragment.getUserVisibleHint() && fragment instanceof FCBaseFragment) {
                    FCBaseFragment f = (FCBaseFragment) fragment;
                    if (f.onBackpressed()) {
                        return true;
                    }
                }
            }
        }
        return false;
    }

    /////////////////////////////////////////////////////////////////////////////////
    //
    //                      释放
    //
    /////////////////////////////////////////////////////////////////////////////////

    @Override
    public void onDestroy() {
        super.onDestroy();
        if (null != unbinder)
            unbinder.unbind();
        mRootView = null;
        //移除eventBus
        if (useEventBus()) {
            EventBus.getDefault().unregister(this);
        }
        if (mPresenter != null) {
            mPresenter.onDestroy();
        }
        if (BuildConfig.DEBUG) {
            Log.e("onDestroy====",getClass().getName()+"onDestroy");
        }
        Glide.with(this).pauseRequests();
    }
}
